package com.hlm.transparent.core.command;

import com.hlm.transparent.util.ComUtil;
import com.hlm.transparent.util.HexUtil;
import com.hlm.transparent.util.ProtocolHelper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;

import java.util.Map;

import static com.hlm.transparent.util.ComUtil.modbusCRC;

/**
 * @program:transparent
 * @description:MODBUS协议命令下发
 * @author: xinY
 **/
public class MODBUSCommand {
    public static ByteBuf packages(String addr, String protocolCode){
        ByteBuf byteBuf = Unpooled.buffer();
        Map<String,Object> sectionMap = ProtocolHelper.getParameterMap(protocolCode,"command");
        Integer variableNum1 = ComUtil.safeInt(sectionMap.get("variablenum1"));
        Integer funcCode = ComUtil.safeInt(sectionMap.get("commandcode"));

        byteBuf.writeByte(HexUtil.intStrToByte(addr)); // 地址
        byteBuf.writeByte(funcCode);// 功能码
        byteBuf.writeByte(0x00);// 寄存器起始位置
        byteBuf.writeByte(0x00);// 寄存器起始位置
        byte[] dataNum= HexUtil.intTo2Byte(variableNum1);
        byteBuf.writeBytes(dataNum);// 寄存器数量
        byte[] bytes = ByteBufUtil.getBytes(byteBuf);
        byte[] checkSum = HexUtil.intTo2Byte(modbusCRC(bytes));
        byteBuf.writeBytes(checkSum);//校验和
        return byteBuf;
    }

}
